package com.eati.cm.ctrler;

import com.eati.cm.excp.BadReqErr;
import com.eati.cm.excp.NoAuthExcp;
import com.eati.cm.view.IResult;
import com.eati.cm.view.Result;
import com.eati.cm.view.ResultStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.error.ErrorAttributeOptions;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

import static javax.servlet.http.MappingMatch.PATH;

@RestController
public class SpringSecurityErrorCtrler implements ErrorController {
    @Autowired
    private ErrorAttributes errorAttributes;

    @RequestMapping(value = "/error")
    void error(HttpServletRequest request, WebRequest webReq, HttpServletResponse response) throws Throwable {
        // Appropriate HTTP response code (e.g. 404 or 500) is automatically set by Spring.
        // Here we just define response body.
        switch(response.getStatus()) {
            case 401: throw new NoAuthExcp("訪問此處須身份驗證。",
                    errorAttributes.getErrorAttributes(webReq, ErrorAttributeOptions.defaults())
                            .get("path").toString(), null
            );
            case 500: throw (Throwable) request.getAttribute("javax.servlet.error.exception"); 
        }
    }

    @Override
    public String getErrorPath() {
        return "/error";
    }
}
